/**
 * @(#)SysMenuImpl.java	07/04/2013
 *
 * Copyright (c) 2013 S9,Inc.All rights reserved.
 * Created by 2013-07-04 
 */
package cn.jdy.authority.service;

import cn.jdy.authority.entity.SysMenu;
import cn.jdy.framework.constant.BaseConstant;
import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.IDUtil;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统菜单接口实现类
 *
 * @author liGan
 * @date: 2013-7-04
 */
@Service
public class SysMenuService extends BaseDao<SysMenu> {
	@Autowired
	RoleMenuService roleMenuService;

	/**
	 * 获得所有菜单信息
	 *
	 * @return List<SysMenu> 菜单集合
	 * @date 2013-7-08
	 * @author liGan
	 */
	public List<SysMenu> listSysMenu(boolean flag) {
		List<SysMenu> listSysMenu;
		try {
			if(flag) {
				DetachedCriteria dc = DetachedCriteria.forClass(super.entityClass);
				dc.addOrder(Order.asc("sort"));
				listSysMenu = super.find(dc);
			} else {
				// 查询所有(启用)菜单
				listSysMenu = super.find("isactive", "1");
			}
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "listSysMenu 获得所有菜单信息有误", e);
			throw new BaseException("获得所有菜单信息有误!", e);
		}
		return listSysMenu;
	}

	/**
	 * 根据userid获取菜单信息
	 */
	public List<SysMenu> findUserMenu(String userid) {
		List<SysMenu> listSysMenu;
		try {
			String sql = "select id, menuname, pid, menuimg, sort, url, isactive, remark from sysmenu" +
					" where isactive = '1' and id in (select distinct menuid from rolemenu" +
					" where roleid in (select u.roleid from userrole u,sysrole r where u.roleid=r.id and r.isactive='1' and u.userid = :userid )) order by sort";
			
//           String sql = "SELECT distinct m.id, m.menuname, m.pid, m.menuimg, m.sort, m.url, m.isactive, m.remark "+ 
//		            "FROM sysmenu m,rolemenu rm,sysrole r,userrole ur "+
//		            "WHERE m.id=rm.menuid AND rm.roleid=r.id AND r.id=ur.roleid "+ 
//		            "AND m.isactive='1' AND r.isactive='1' AND ur.userid=:userid "+ 
//		            "ORDER BY m.sort";

			SQLQuery query = super.em().createSQLQuery(sql).addEntity(SysMenu.class);
			query.setParameter("userid", userid);
			listSysMenu = query.list();
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "findUserMenu", e);
			throw new BaseException("获得用户菜单信息有误!", e);
		}
		return listSysMenu;
	}

	public List<SysMenu> getUserMenu(String userId) {
		List<SysMenu> topMenu = new ArrayList<SysMenu>();
		List<SysMenu> twoMenu = new ArrayList<SysMenu>();
		try {
			// 获得系统所有菜单
			List<SysMenu> listSysMenu = findUserMenu(userId);
			if(listSysMenu != null && listSysMenu.size() != 0) {
				for(SysMenu menu : listSysMenu) {
					if(BaseConstant.TOP_SYSMENU_CODE.equals(menu.getPid())) {
						// 获得顶级菜单
						topMenu.add(menu);
					} else {
						// 获得二级菜单
						twoMenu.add(menu);
					}
				}
				List<SysMenu> twoList = null;
				boolean flag;
				for(SysMenu topM : topMenu) {
					twoList = new ArrayList<SysMenu>();
					flag = false;
					for(SysMenu twoM : twoMenu) {
						if(topM.getId().equals(twoM.getPid())) {
							twoM.setPmenuName(topM.getMenuname());
							twoList.add(twoM);
							flag = true;
						}
					}
					if(flag) {
						topM.setChildren(twoList);
					}
				}
			}
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "listSysMenu 显示系统所有菜单信息有误", e);
		}
		return topMenu;
	}

	/**
	 * 修改菜单状态
	 *
	 * @return void
	 * @date 2013-7-08
	 * @author liGan
	 */
	@Transactional
	public void updSysMenuStatus(String menuid, String isactive) {
		try {
			Query query = super.em().createSQLQuery("update sysmenu set isactive = :isactive where id = :id");
			query.setParameter("isactive", isactive);
			query.setParameter("id", menuid);
			query.executeUpdate();
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "updSysMenuStatus 修改菜单状态有误", e);
			throw new BaseException("修改菜单状态有误!", e);
		}
	}

	/**
	 * 查看菜单详细信息
	 */
	public SysMenu showSysMenu(String id) {
		SysMenu menu;
		try {
			menu = super.findOne("id", id);
			SysMenu parent = super.findOne("id", menu.getPid());
			if(parent != null) menu.setPmenuName(parent.getMenuname());
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "showSysMenu 查看系统菜单信息有误", e);
			throw new BaseException("查看系统菜单信息有误!", e);
		}
		return menu;
	}

	/**
	 * 添加角色菜单权限
	 */
	@Transactional
	public void addRoleMenu(String roleid, String menuid) {
		String[] mid = menuid.split(",");
		try {
			// 删除原有数据
			Query query = super.em().createSQLQuery("delete from rolemenu where roleid = :roleid");
			query.setParameter("roleid", roleid);
			query.executeUpdate();

			for(int i = 0; i < mid.length; i++) {
				query = super.em().createSQLQuery("insert into rolemenu (id, roleid, menuid) values (:id, :roleid, :menuid)");
				query.setParameter("id", IDUtil.getID());
				query.setParameter("roleid", roleid);
				query.setParameter("menuid", mid[i]);
				query.executeUpdate();
			}
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "addRoleMenu:批量添加角色菜单权限有误", e);
			throw new BaseException("批量添加角色菜单权限有误", e);
		}
	}

	/**
	 * 获得角色菜单权限
	 * <p/>
	 * String roleId 角色ID
	 *
	 * @return List<String> 菜单ID列表
	 * @date 2013-7-08
	 * @author liGan
	 */
	public List<String> findRoleMenu(String roleId) {
		List<String> list;
		try {
			Query query = super.em().createSQLQuery("select menuid from rolemenu where roleid = :roleid");
			query.setParameter("roleid", roleId);
			list = query.list();
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "findRoleMenu:获得角色菜单权限异常!", e);
			throw new BaseException("获得角色菜单权限异常!", e);
		}
		return list;
	}

	/**
	 * 删除菜单
	 * String roleId 角色ID
	 *
	 * @return void
	 * @date 2013-12-12 22:50
	 * @author wuzhiliang
	 */
	@Transactional
	public void delSysMenu(String sysMenuIds) {
		try {
			// 删除子菜单与角色对应关系
			String [] ids = sysMenuIds.split(",");
			for (String id : ids) {
				List<SysMenu> menus = super.find("pid", id);
				if (menus != null && menus.size() > 0) {
					String [] menuids = new String[menus.size()] ;
					int i = 0;
					for (SysMenu menu : menus) {
						menuids[i] = menu.getId();
						i++;
					}
					if (menuids != null) {
						roleMenuService.delete(menuids, "menuid");
					}
				}
			}
			
			// 删除菜单与角色对应关系
			roleMenuService.delete(ids, "menuid");
			
			// 删除菜单
			super.delete(ids, "id");

			// 删除子菜单
			super.delete(ids, "pid");
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "delSysMenu 删除菜单信息出错！", e);
		}
	}

}
